package cn.com.ccxe.service;

import java.util.ArrayList;
import java.util.List;

import cn.com.ccxe.core.entity.Keyword;
import cn.com.ccxe.core.util.KeywordSet;
import cn.com.ccxe.dao.KeywordDao;
import cn.com.ccxe.dao.impl.KeywordDaoImpl;

public class SearchBussiness {

	private KeywordDao keywordDao = new KeywordDaoImpl();
	public String getKeywordRole(int favoriteId) {
		List<Keyword> keywords = keywordDao.getKeywordByFavoriteId(favoriteId);
		if(keywords != null && keywords.size() > 0) {
			KeywordSet keywordSet = new KeywordSet();
			keywordSet.add(keywords);
			return keywordSet.toRule();
		}
		return "";
	}
	
	public String getKeyword(String text) {
		if(validateCharset(text)) {
			List<Keyword> keywords = keywordDao.getKeyword(text);
			String jsonData = keyword2Json(keywords);
			return jsonData;
		}
		return "[]";
	}
	
	private boolean validateCharset(String text) {
		int ascll = Integer.valueOf(text.charAt(0));
		return ascll == 83 || ascll == 115 || ascll > 200;
	}
	
	public String keyword2Json(List<Keyword> keywords) {
		if(keywords == null || keywords.size() <= 0) {
			return "[]";
		}
		StringBuilder sb = new StringBuilder("[");
		for (Keyword k : keywords) {
			sb.append("{\"text\":\"").append(k.getText()).append("\"},");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("]");
		return sb.toString();
	}
	
	public static void main(String[] args) {
		List<Keyword> keywords = new ArrayList<Keyword>();
		for (int i = 0; i < 2; i++) {
			Keyword keyword = new Keyword(i);
			keyword.setText("关键字"+i);
			keywords.add(keyword);
		}
		SearchBussiness bussiness = new SearchBussiness();
		String json = bussiness.keyword2Json(keywords);
		System.out.println(json);
	}
}
